package com.xf;

import com.xf.common.Invocation;
import com.xf.protocol.HttpClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {
    private String version;//调用的服务接口的版本
    private String RigistAddress;//注册中心ip地址
    private Integer port;//注册中心端口

    public MyInvocationHandler(String rigistAddress, Integer port, String version) {
        this.port = port;
        RigistAddress = rigistAddress;
        this.version = version;
    }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String intefacename = proxy.getClass().getInterfaces()[0].getName();
            String version=this.version;
            String methodname = method.getName();
            Object[] parameters=args;
            Class[] parameterTypes=new Class[parameters.length];
            for (int i = 0; i < parameters.length; i++){
                parameterTypes[i]=parameters[i].getClass();
            }
            Invocation invocation = new Invocation(intefacename, methodname, parameterTypes, parameters, version);
            HttpClient httpClient2=new HttpClient();
            Object result = httpClient2.cfs_con_rig(RigistAddress, port, invocation);

            Class<?> returnType = method.getReturnType();
            if (!returnType.isInstance(result)) {
                // 如果不匹配，可以选择抛出异常或者返回一个默认值
                throw new RuntimeException("处理结果有其他消息："+(String) result);
            }

            return result;
        }
    }
